const { schema } = require("../pipe/user")
const { sha256Hash } = require("../tools/hash")
const jsonwebtoken = require("jsonwebtoken")

/**
 * @type {Custom.Controller<"login">}
 */
module.exports = {
    async login(ctx, next) {
        const {
            username,
            password
        } = await schema.login.validateAsync(ctx.request.body)

        const user = await ctx.model.User.findOne({
            where: { username }
        })

        if (!user) {
            return ctx.fail("用户不存在, 请重新确认用户名", 400)
        }

        const passwordIsEqual =
            user.password ===
            sha256Hash(password, ctx.config.SECRET_KEY.PASSWORD)

        if (!passwordIsEqual) {
            return ctx.fail("密码错误, 请重新确认密码", 400)
        }

        const payload = {
            id: user.id,
            username: user.username
        }

        const token = jsonwebtoken.sign(
            payload,
            ctx.config.SECRET_KEY.TOKEN,
            /*过期的时间*/
            { expiresIn: "7d" }
        )

        ctx.success({...payload, token })
        await next()
    }
}